<?php
namespace app\store\controller\market;
use app\store\controller\Controller;
use app\store\model\Setting as SettingModel;

/**
 * 分销商配置控制器
 */
class Free extends Controller
{
    /**
     * 更新设置
     */
    public function setting()
    {
        if (!$this->request->isAjax()) {
            $values = SettingModel::getItem('free');
			if(!empty($values['start_time']) OR !empty($values['end_time'])){
				$values['start_time'] = date('Y-m-d H:i:s',$values['start_time']);
				$values['end_time'] = date('Y-m-d H:i:s',$values['end_time']);
			}
            return $this->fetch('setting', compact('values'));
        }
        $model = new SettingModel;
		$data = $this->postData('free');
		if(empty($data['start_time'])){
			return $this->renderError('开始日期不可为空');
		}
		if(empty($data['end_time'])){
			return $this->renderError('结束日期不可为空');
		}
		if(date('Y-m-d H:i:s',strtotime($data['start_time'])) != $data['start_time']){
			return $this->renderError('开始日期时间格式不对');
		}
		if(date('Y-m-d H:i:s',strtotime($data['end_time'])) != $data['end_time']){
			return $this->renderError('结束日期时间格式不对');
		}
		$data['start_time'] = strtotime($data['start_time']);
		$data['end_time'] = strtotime($data['end_time']);
		if($data['start_time']<time()){
			return $this->renderError('开始日期时间不能小于当前日期时间');
		}
		if($data['start_time']>$data['end_time']){
			return $this->renderError('结束日期时间不能小于开始日期时间');
		}
        if ($model->edit('free',$data)) {
            return $this->renderSuccess('更新成功');
        }
        $error = $model->getError() ?: '更新失败';
        return $this->renderError($error);
    }
}
